﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLogic.Security;
using System.Configuration;
using Otgruzka.ServicesClients;
using Otgruzka.Controls.jQuery;
using DataTier;
using DataTier.Entities;
using System.ServiceModel;

namespace Otgruzka.Controls.ExpendBill
{
    public partial class ExpendBillAllList : System.Web.UI.UserControl
    {
        /// <summary>
        /// Свойство, указывающее на наличие фильтра
        /// </summary>
        protected bool IsFiltered
        {
            get { return Session["SearchParameters"] != null && Session["SearchParameters"] is SearchParameters; }
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            SearchParameters searchParameters = null;

            if (IsPostBack)
            {
                // Заполняется объект SearchParameters
                searchParameters = GetSearchParameters();

                // SearchParameters добавляется в сессию
                Session["SearchParameters"] = searchParameters;
            }

            BindPaging(searchParameters);
            if (!IsPostBack)
                Bind();
            FillFiltersFields();
        }

        private void Bind()
        {
            var expendBills = GetExpendBills();

            if (expendBills != null)
                this.ExpendBills.DataSource = expendBills.ToList();

            this.ExpendBills.DataBind();
        }

        private void BindPaging(SearchParameters searchParameters)
        {
            int? numRows = new ExpendBillsClient().GetExpendBillAllListCount(UserPrincipal.Current.UserId, searchParameters);

            this.PagingTop.CountRows = numRows;
            this.PagingTop.NumPageSessionName = "billsNumPage";
            this.PagingTop.PageNumberChange += new Paging.PageNumberChangeHandler(PagingTop_PageNumberChange);

            this.PagingBottom.CountRows = numRows;
            this.PagingBottom.NumPageSessionName = "billsNumPage";
            this.PagingBottom.PageNumberChange += new Paging.PageNumberChangeHandler(PagingBottom_PageNumberChange);
        }

        void PagingBottom_PageNumberChange(object sender, PageNumberChangeEventArgs data)
        {
            this.PagingTop.Bind();
            Bind();
            FillFiltersFields(); // Заполняются поля ввода для фильтров из Session
        }

        void PagingTop_PageNumberChange(object sender, PageNumberChangeEventArgs data)
        {
            this.PagingBottom.Bind();
            Bind();
            FillFiltersFields(); // Заполняются поля ввода для фильтров из Session
        }


        protected void ExpendBillList_Filtr_click(object sender, EventArgs e)
        {
            //// Заполняются поля ввода для фильтров из Session
            //FillFiltersFields();
            //SearchParameters searchParameters = null;
            //searchParameters = GetSearchParameters();

            //var bills = GetExpendBills();
            //if (bills != null && bills.Count > 0)
            //{
            //    //this.Orders.DataSource = orders.Where(o => o.Id == Convert.ToInt32(this.search_id.Text));

            //    // Номер заказа
            //    if (searchParameters.OrderNumber != null)
            //        this.ExpendBills.DataSource = bills.Where(b => b.Order.Header.Number.ToLower().Contains(searchParameters.OrderNumber.ToLower()));

            //    // Дата заказа
            //    if (searchParameters.OrderCreatedDate != null)
            //        this.ExpendBills.DataSource = bills.Where(b => b.Order.Header.CreatedDate.Date.ToShortDateString().Contains(searchParameters.OrderCreatedDate.Value.Date.ToShortDateString()));

            //    // Номер накладной
            //    if (searchParameters.ExpendBillNumberTotal != null)
            //        this.ExpendBills.DataSource = bills.Where(b => b.ExpendBill.NumberTotal.ToLower().Contains(searchParameters.ExpendBillNumberTotal.ToLower()));

            //    // Дата накладной
            //    if (searchParameters.ExpendBillDate != null)
            //        this.ExpendBills.DataSource = bills.Where(b => b.ExpendBill.CreatedDate.Date.ToShortDateString().Contains(searchParameters.ExpendBillDate.Value.Date.ToShortDateString()));

            //    this.ExpendBills.DataBind();
            //}
            this.PagingTop.CurrentPageNumber = 1;
            this.PagingBottom.CurrentPageNumber = 1;

            BindAndFillFiltersPaging();
        }


        /// <summary>
        /// Заполняются поля ввода для фильтров из Session
        /// </summary>
        private void FillFiltersFields()
        {
            var searchParameters = Session["SearchParameters"] as SearchParameters;
            if (searchParameters != null)
            {
                #region Заполняются поля ввода фильтров

                var HExpendBillNumberTotal = this.ExpendBills.HeaderRow.FindControl("HExpendBillNumberTotal") as TextBox;
                var HExpendBillDate = this.ExpendBills.HeaderRow.FindControl("HExpendBillDate") as jQuery.JQueryDatepicker;
                var HOrderNumber = this.ExpendBills.HeaderRow.FindControl("HOrderNumber") as TextBox;
                var HOrderCreatedDate = this.ExpendBills.HeaderRow.FindControl("HOrderCreatedDate") as jQuery.JQueryDatepicker;
                var HExpendBillStateName = this.ExpendBills.HeaderRow.FindControl("HExpendBillStateName") as TextBox;
                var HOrderDepartmentName = this.ExpendBills.HeaderRow.FindControl("HOrderDepartmentName") as TextBox;
                var HOrderCostCenterName = this.ExpendBills.HeaderRow.FindControl("HOrderCostCenterName") as TextBox;
                var HOrderJuridicalPersonName = this.ExpendBills.HeaderRow.FindControl("HOrderJuridicalPersonName") as TextBox;

                if (HExpendBillNumberTotal != null)
                    HExpendBillNumberTotal.Text = searchParameters.ExpendBillNumberTotal;

                if (HExpendBillDate != null)
                    HExpendBillDate.SelectedDate = searchParameters.ExpendBillDate;

                if (HOrderNumber != null)
                    HOrderNumber.Text = searchParameters.OrderNumber;

                if (HOrderCreatedDate != null)
                    HOrderCreatedDate.SelectedDate = searchParameters.OrderCreatedDate;

                if (HExpendBillStateName != null)
                    HExpendBillStateName.Text = searchParameters.ExpendBillStatus;

                if (HOrderDepartmentName != null)
                    HOrderDepartmentName.Text = searchParameters.Department;

                if (HOrderCostCenterName != null)
                    HOrderCostCenterName.Text = searchParameters.CostsCentr;

                if (HOrderJuridicalPersonName != null)
                    HOrderJuridicalPersonName.Text = searchParameters.JuridicalPerson;

                #endregion Заполняются поля ввода фильтров
            }
        }


        /// <summary>
        /// Возвращается объект SearchParameters формирующийся из полей ввода фильтров
        /// </summary>
        /// <returns></returns>
        private SearchParameters GetSearchParameters()
        {
            // Создаем экземпляр SearchParameters
            SearchParameters searchParameters = new SearchParameters();

            #region Заполняется объект SearchParameters


            var HExpendBillNumberTotal = this.ExpendBills.HeaderRow.FindControl("HExpendBillNumberTotal") as TextBox;
            var HExpendBillDate = this.ExpendBills.HeaderRow.FindControl("HExpendBillDate") as jQuery.JQueryDatepicker;
            var HOrderNumber = this.ExpendBills.HeaderRow.FindControl("HOrderNumber") as TextBox;
            var HOrderCreatedDate = this.ExpendBills.HeaderRow.FindControl("HOrderCreatedDate") as jQuery.JQueryDatepicker;
            var HExpendBillStateName = this.ExpendBills.HeaderRow.FindControl("HExpendBillStateName") as TextBox;
            var HOrderDepartmentName = this.ExpendBills.HeaderRow.FindControl("HOrderDepartmentName") as TextBox;
            var HOrderCostCenterName = this.ExpendBills.HeaderRow.FindControl("HOrderCostCenterName") as TextBox;
            var HOrderJuridicalPersonName = this.ExpendBills.HeaderRow.FindControl("HOrderJuridicalPersonName") as TextBox;

            if (HExpendBillNumberTotal != null && !string.IsNullOrEmpty(HExpendBillNumberTotal.Text))
                searchParameters.ExpendBillNumberTotal = HExpendBillNumberTotal.Text;

            if (HExpendBillDate != null && HExpendBillDate.SelectedDate.HasValue)
                searchParameters.ExpendBillDate = HExpendBillDate.SelectedDate.Value;

            if (HOrderNumber != null && !string.IsNullOrEmpty(HOrderNumber.Text))
                searchParameters.OrderNumber = HOrderNumber.Text;

            if (HOrderCreatedDate != null && HOrderCreatedDate.SelectedDate.HasValue)
                searchParameters.OrderCreatedDate = HOrderCreatedDate.SelectedDate.Value;

            if (HExpendBillStateName != null && !string.IsNullOrEmpty(HExpendBillStateName.Text))
                searchParameters.ExpendBillStatus = HExpendBillStateName.Text;

            if (HOrderDepartmentName != null && !string.IsNullOrEmpty(HOrderDepartmentName.Text))
                searchParameters.Department = HOrderDepartmentName.Text;

            if (HOrderCostCenterName != null && !string.IsNullOrEmpty(HOrderCostCenterName.Text))
                searchParameters.CostsCentr = HOrderCostCenterName.Text;

            if (HOrderJuridicalPersonName != null && !string.IsNullOrEmpty(HOrderJuridicalPersonName.Text))
                searchParameters.JuridicalPerson = HOrderJuridicalPersonName.Text;

            // Если все поля с фильтрами пустые, то объект с параметрами приравнивается NULL
            if ((HExpendBillNumberTotal == null || string.IsNullOrEmpty(HExpendBillNumberTotal.Text)) &&
                (HExpendBillDate == null || !HExpendBillDate.SelectedDate.HasValue) &&
                (HOrderNumber == null || string.IsNullOrEmpty(HOrderNumber.Text)) &&
                (HOrderCreatedDate == null || !HOrderCreatedDate.SelectedDate.HasValue) &&
                (HExpendBillStateName == null || string.IsNullOrEmpty(HExpendBillStateName.Text)) &&
                (HOrderDepartmentName == null || string.IsNullOrEmpty(HOrderDepartmentName.Text)) &&
                (HOrderCostCenterName == null || string.IsNullOrEmpty(HOrderCostCenterName.Text)) &&
                (HOrderJuridicalPersonName == null || string.IsNullOrEmpty(HOrderJuridicalPersonName.Text)) 
            )
            {
                searchParameters = null;// searchParameters = (Session["SearchParameters"] != null) ? Session["SearchParameters"] as SearchParameters : null;
            }

            #endregion Заполняется объект SearchParameters
            { }
            return searchParameters;
        }


        protected void ExpendBillList_Clear_Filtr(object sender, EventArgs e)
        {
            Session["SearchParameters"] = null;
            this.PagingTop.CurrentPageNumber = 1;
            this.PagingBottom.CurrentPageNumber = 1;
            Response.Redirect("~/WebForms/ExpendBillAllList.aspx");
        }


        private List<ExpendBillEntity> GetExpendBills()
        {
            var client = new ExpendBillsClient();
            try
            {
                int numPage = this.PagingTop.CurrentPageNumber;
                int onPage = (ConfigurationManager.AppSettings["RowsOnPage"] != null) ? Convert.ToInt32(ConfigurationManager.AppSettings["RowsOnPage"]) : 11;

                var searchParameters = (Session["SearchParameters"] != null) ? Session["SearchParameters"] as SearchParameters : null;
                var expendBills = client.GetExpendBillAllList(UserPrincipal.Current.UserId, numPage, onPage, searchParameters);

                return expendBills;
            }
            catch (System.ServiceModel.FaultException<ExceptionDetail> ex)
            {
                string message = client.GetExceptionDetail(ex);
                this.ErrorMessage.Text = message;
                return null;
            }
            catch (System.Exception exp)
            {
                this.ErrorMessage.Text = exp.Message;
                return null;
            }
        }


        protected void ExpendBills_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                int id = Convert.ToInt32(ExpendBills.SelectedRow.Cells[0].Text);
                int orderId = Convert.ToInt32(ExpendBills.SelectedRow.Cells[2].Text);
                Response.Redirect(string.Format("~/WebForms/ExpendBillDetails.aspx?oid={0}&exbid={1}", orderId, id));
            }
            catch (Exception ex)
            { }
        }


        /// <summary>
        /// Событие заполнения строки грида данными
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ExpendBills_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                int expendedBillId = 0;
                var dataItem = e.Row.DataItem as DataTier.ExpendBill;
                if (dataItem != null)
                {
                    expendedBillId = dataItem.Id;
                }

                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    e.Row.Attributes["onmouseover"] = "this.style.backgroundColor='#6b8cbe'";
                    e.Row.Attributes["onmouseout"] = "this.style.backgroundColor='#FFFFFF'";
                    e.Row.Attributes["style"] = "cursor:hand;background-color: #FFFFFF";

                    var grid = sender as GridView;
                    string postback = Page.ClientScript.GetPostBackEventReference(grid, string.Format("Select${0}", e.Row.RowIndex));
                    e.Row.Attributes.Add("onclick", postback.ToString());
                }
            }
        }


        /// <summary>
        /// Событие нажатия на LinkButton для редактирования Заказа
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ExpendedBillEditButton_Click(object sender, EventArgs e)
        {
            try
            {
                string[] arguments = (sender as LinkButton).CommandArgument.Split('|');
                int orderId = Convert.ToInt32(arguments[1]);
                int expendedBillId = Convert.ToInt32(arguments[0]);
                Response.Redirect(string.Format("~/WebForms/ExpendBillDetails.aspx?oid={0}&exbid={1}", orderId, expendedBillId));
            }
            catch (Exception ex)
            { }
        }


        private void BindAndFillFiltersPaging()
        {
            SearchParameters searchParameters = null;
            searchParameters = GetSearchParameters();
            BindPaging(searchParameters);
            Bind();
            FillFiltersFields();
        }

    }
}